﻿using Autofac;
using IoTAdapter.BaseCore;
using IoTAdapter.Clients.Siemens;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SqlSugar;
using Warehouse.Entites;
using Warehouse.Services.Repository;
using WCS.Entities;
using WCS.Entities.Enum;
using WCS.IServices;

namespace WCS.Services.JobCreateService
{

    /// <summary>
    /// 任务创建服务
    /// </summary>
    public class CreateJobService : ICreateJob
    {
        private readonly ILogger<CreateJobService> logger;
        private readonly IOptionsMonitor<Dictionary<string, int>> stackerConfig;
        private readonly ILifetimeScope lifetimeScope;
        private readonly Repository<Material> materialRepository;
        private readonly Repository<WareHouse> WareHouseRepository;


        public CreateJobService(
            ILogger<CreateJobService> logger,
            IOptionsMonitor<Dictionary<string, int>> stackerConfig,
            ILifetimeScope lifetimeScope,
            Repository<Material> materialRepository, Repository<WareHouse> WareHouseRepository)
        {
            this.logger = logger;
            this.stackerConfig = stackerConfig;
            this.lifetimeScope = lifetimeScope;
            this.materialRepository = materialRepository;
            this.WareHouseRepository = WareHouseRepository;
        }

        /// <summary>
        /// 创建任务
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public async Task CreateJob(TransferPort port, List<TransferPort> ports)
        {

            //using var scope = lifetimeScope.BeginLifetimeScope();
            //var db = scope.Resolve<ISqlSugarClient>().CopyNew();
            //try
            //{
            //    if (port.CallType == TaskType.OutStorage)
            //    {
            //        var materials = await materialRepository.QueryAsync();
            //        var materialList = new List<Material>();
            //        var numberSameCount = materials.Where(i => i.IsOutStorage == false).OrderBy(i => i.Creator_time).GroupBy(i => i.MaterialNumber, i => i.Id).Where(i => i.Count() > 1).ToList();
            //        if (numberSameCount.Count >= 30)
            //        {
            //            foreach (var material in numberSameCount)
            //            {
            //                materialList = materials.Where(i => i.MaterialNumber == material.Key).ToList();
            //            }
            //        }
            //        if (materialList.Count > 0 && materialList.Count == 30)
            //        {
            //            foreach (var item in materialList)
            //            {
            //                var storageInfo = await WareHouseRepository.FindAsync(item.LocationNumber);
            //                if (storageInfo != null)
            //                {
            //                    storageInfo.CurrentQuantity--;
            //                    item.IsOutStorage = true;
            //                    await materialRepository.UpdateAsync(item);
            //                    await WareHouseRepository.Context.CopyNew().Updateable(storageInfo).UpdateColumns(i => new { i.CurrentQuantity }).ExecuteCommandAsync();
            //                }
            //                if (!string.IsNullOrEmpty(item.MaterialNumber))
            //                {
            //                    if (port.ResponseCall())
            //                    {
            //                        var job = new Job(port)
            //                        {
            //                            Action = OperationType.Put,
            //                            Content = item.MaterialNumber
            //                        };
            //                        var isOk = await db.Insertable(new Job[] { job }).ExecuteCommandAsync();
            //                        if (isOk > 0)
            //                        {
            //                            //#region 第二种方法

            //                            //// 任务 ID
            //                            //port.BelongDevice.Operation.Write("0", job.Id);

            //                            //// 下发的源排
            //                            //port.BelongDevice.Operation.Write("4", storageInfo.Arrange);

            //                            //// 下发的源列                            剩余空位数（4）= 总数（5）- 当前数（1）
            //                            //port.BelongDevice.Operation.Write("6", storageInfo.CountColumns - storageInfo.CurrentColumnsNumber);

            //                            //// 下发的源层                            剩余空层数（4）= 总数（5）- 当前数（1）
            //                            //port.BelongDevice.Operation.Write("8", storageInfo.CountStorey - storageInfo.CurrentStoreyNumber);

            //                            //// 下发的目标排
            //                            //port.BelongDevice.Operation.Write("10", item.TargetPlatoon);

            //                            //// 下发的目标列
            //                            //port.BelongDevice.Operation.Write("12", item.TargetColumn);

            //                            //// 下发的目标层
            //                            //port.BelongDevice.Operation.Write("14", item.TargetLayer);

            //                            //// 任务类型 1：取放（去源位置取货，目标位置放货）；2：取货（去源位置取货）；3：放货（去目标位置放货）；4：行走（移动到源位置）；5：预留；6：预留；7：任务删除；
            //                            //port.BelongDevice.Operation.Write("16", (ushort)1);

            //                            //// 预留
            //                            //port.BelongDevice.Operation.Write("18", "");

            //                            //// 校验码 = 下发的源排 + 下发的源列 + 下发的源层 + 下发的目标排 + 下发的目标列 + 下发的目标层 + 任务类型
            //                            //port.BelongDevice.Operation.Write("20", "");

            //                            //// 1：任务下发完成，启动下发的任务写1; 0：堆垛机响应任务后，堆垛机PLC置为0
            //                            //port.BelongDevice.Operation.Write("24", (ushort)1);

            //                            //#endregion

            //                            job.Status = TaskState.Excuting;
            //                            await db.Updateable(job).UpdateColumns(i => new { i.Status }).ExecuteCommandAsync();
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //        else
            //        {
            //            logger.LogInformation($"出库失败，出库数量不足");
            //        }
            //    }
            //    else if (port.CallType == TaskType.PutStorage)
            //    {
            //        var storages = await WareHouseRepository.QueryAsync();
            //        var storageInfo = new Storage();
            //        if (storages.Count > 0)
            //        {
            //            storageInfo = storages.Where(i => !i.IsFull).OrderByDescending(i => i.CurrentNumber).FirstOrDefault();
            //            if (storageInfo != null)
            //            {
            //                //if (storageInfo.Content == addMateria.MaterialNumber)
            //                //{
            //                //    storageInfo.CurrentNumber++;
            //                //}
            //                //else if (string.IsNullOrEmpty(storageInfo.Content))
            //                //{
            //                //    storageInfo.CurrentNumber++;
            //                //    storageInfo.Content = addMateria.MaterialNumber;
            //                //}
            //                if (storageInfo.CountColumns != storageInfo.CurrentColumns)
            //                {
            //                    if (storageInfo.CurrentColumnsNumber == storageInfo.CurrentColumnsCount)
            //                    {
            //                        storageInfo.CurrentColumns++;
            //                        storageInfo.CurrentColumnsNumber = 0;
            //                        storageInfo.CurrentStoreyNumber = 0;
            //                        await storageRepository.Context.CopyNew().Updateable(storageInfo).UpdateColumns(i => new { i.CurrentColumns, i.CurrentColumnsNumber, i.CurrentStoreyNumber }).ExecuteCommandAsync();
            //                    }
            //                    storageInfo.CurrentColumnsNumber++;
            //                    storageInfo.CurrentStoreyNumber++;
            //                    storageInfo.CurrentNumber++;
            //                    await storageRepository.Context.CopyNew().Updateable(storageInfo).UpdateColumns(i => new { i.CurrentColumnsNumber, i.CurrentStoreyNumber, i.CurrentNumber }).ExecuteCommandAsync();

            //                    var job = new Job(port)
            //                    {
            //                        Action = OperationType.Put,
            //                    };
            //                    var isOk = await db.Insertable(new Job[] { job }).ExecuteCommandAsync();
            //                    if (isOk > 0)
            //                    {
            //                        #region 最初写法

            //                        //// 任务 ID
            //                        //port.BelongDevice.Operation.Write("0", job.Id);

            //                        //// 下发的源排
            //                        //port.BelongDevice.Operation.Write("4", "");

            //                        //// 下发的源列
            //                        //port.BelongDevice.Operation.Write("6", "");

            //                        //// 下发的源层
            //                        //port.BelongDevice.Operation.Write("8", "");

            //                        //// 下发的目标排
            //                        //port.BelongDevice.Operation.Write("10", "");

            //                        //// 下发的目标列
            //                        //port.BelongDevice.Operation.Write("12", "");

            //                        //// 下发的目标层
            //                        //port.BelongDevice.Operation.Write("14", "");

            //                        //// 任务类型 1：取放（去源位置取货，目标位置放货）；2：取货（去源位置取货）；3：放货（去目标位置放货）；4：行走（移动到源位置）；5：预留；6：预留；7：任务删除；
            //                        //port.BelongDevice.Operation.Write("16", (ushort)2);

            //                        //// 预留
            //                        //port.BelongDevice.Operation.Write("18", "");

            //                        //// 校验码 = 下发的源排 + 下发的源列 + 下发的源层 + 下发的目标排 + 下发的目标列 + 下发的目标层 + 任务类型
            //                        //port.BelongDevice.Operation.Write("20", "");

            //                        //// 1：任务下发完成，启动下发的任务写1; 0：堆垛机响应任务后，堆垛机PLC置为0
            //                        //port.BelongDevice.Operation.Write("24", (ushort)1);

            //                        #endregion

            //                        var jobNumber = DateTime.Now.ToString("yyMMddHHmmssfff");
            //                        var result = stackerHelper.PutStroage(Convert.ToInt32(jobNumber), storageInfo.Arrange, storageInfo.CurrentColumns, storageInfo.CurrentStoreyNumber, storageInfo.Arrange, storageInfo.CurrentColumns, storageInfo.CurrentStoreyNumber);

            //                        if (result)
            //                        {
            //                            job.Status = TaskState.Excuting;
            //                            await db.Updateable(job).UpdateColumns(i => new { i.Status }).ExecuteCommandAsync();
            //                        }
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    logger.LogError($"创建出库任务异常：{ex.Message}");
            //}
        }
    }
}

